/**
 * @description  : 离线缓存数据 数据库表操作API 封装
 * @descriptionDetail : 离线缓存数据 数据库表操作API 封装
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-12-03 13:55:10
 */
import webDB from '@/common/database.js';
import {
  v4 as uuidv4,
} from 'uuid';
import {
  goods,
} from './sql.js';

//  涉案物品
const goodsService = {
  //  保存数据
  saveGoodsDb: function(obj) {
    return new Promise(function(resolve, reject) {
      if(obj.content.length == 0) {
        reject();
        return;
      }
      if (webDB.isEmpty(obj.tid)) { //  如果id是空 表示新增
        obj.tid = uuidv4();
        webDB.insterData(goods.insertSQL, [obj.tid, obj.caseCode, obj.userId, escape(JSON.stringify(obj.content)),],
          goods.createSQL_H5).then(res => {
          resolve(obj.tid);
        }).catch(e => {
          reject();
        });
      } else { // 否则是修改
        webDB.updateDataBatch("GOODS", 
          {content:escape(JSON.stringify(obj.content)),},
          {tid : obj.tid,},
          goods.createSQL_H5
        ).then(() => {
          resolve();
        }).catch(e => {
          reject();
        });
      }
    });
  },
  // 获取保存数据
  getGoodsDb: function(caseCode, userId) {
    return new Promise(function(resolve, reject) {
      webDB.findData(goods.queryWhereSQL, 
        [caseCode,userId,],
        goods.createSQL_H5, 
        goods.createSQL_H5.queryKeys)
        .then(res => {
          if(res && res.length > 0){
            let retpm = res[0];
            let op = {};
            op.content = JSON.parse(unescape(retpm['content']));
            op.tid = retpm['tid'];
            op.caseCode = retpm['caseCode'];
            op.userId = retpm['userId'];
            resolve(op);
          }else{
            resolve();
          }
        }).catch(e => {
          resolve();
        });
    });
  },
  delGoodsDb: function(caseCode, userId){
    return new Promise(function(resolve, reject) {
      webDB.deleteData(goods.createSQL_H5.name, 
        {
          caseCode:caseCode,
          userId:userId,
        })
        .then(res => {
          resolve();
        }).catch(e => {
          resolve();
        });
    });
  },
}

module.exports = {
  goodsService,
}
